<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="16">
        <div class="menu">
          <el-button type="text" @click="nonDrugTableOpenAndClose" class="el-icon-circle-plus-outline" v-hasPermi="['dms:drug_model:add']">新增处方</el-button>
          <el-button type="text" @click="delDrugInDealWithDrugTable" class="el-icon-remove-outline">删除处方</el-button>
          <el-button type="text" @click="addDrugInDealWithDrug" class="el-icon-success">开立处方</el-button>
          <el-button type="text" @click="delDrugDealWith" class="el-icon-error">作废处方</el-button>
          <el-button type="text" @click="$alert('暂存')" class="el-icon-upload2">暂存</el-button>
          <el-button type="text" @click="$alert('取出暂存')" class="el-icon-download">取出暂存</el-button>
          <el-button type="text" @click="getList()" class="el-icon-refresh">刷新</el-button>
          <hr/>
          <div>
            <el-tag type="danger">总计:{{amounts}}元</el-tag>
          </div>
        </div>
        <el-table :data="this.tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column align="center" label="项目编码" prop="nonDrug.code"/>
          <el-table-column align="center" label="项目名称" prop="nonDrug.name"/>
          <el-table-column align="center" label="执行科室" prop="nonDrug.deptName"/>
          <el-table-column align="center" label="单位" prop="nonDrug.format"/>
          <el-table-column align="center" label="单价" prop="nonDrug.price"/>
          <el-table-column align="center" label="状态" prop="status" :formatter="statusFormat"/>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-tag type="warning" v-if="scope.row.id==null" @click="showNonDrug(scope.row)">检查执行</el-tag>
              <el-tag type="warning" v-if="scope.row.id!=null" >执行完毕</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="科室ID" prop="nonDrug.deptId" v-if="false"/>
        </el-table>
      </el-col>
      <el-col :span="8">
        <el-tabs type="card" style="padding: 20px">
          <el-tab-pane label="模板检查" name="non_drug_model_table">
            <el-table :data="nonDrug_modelList" @row-click="getNonDrugModelById">
              <el-table-column align="center" label="模版ID" prop="id" v-if="false"/>
              <el-table-column align="center" label="模版名" prop="name"/>
              <el-table-column align="center" label="模板简介" prop="aim"/>
            </el-table>
            <br/>
            <div>
              <el-row>
                <el-tag>模版详情</el-tag>
              </el-row>
              <el-row>
                <el-input v-model="non_drug_model_info.name" disabled="disabled">
                  <template slot="prepend" style="width: 30px">名称:</template>
                </el-input>
              </el-row>
              <el-row>
                <el-input v-model="non_drug_model_info.code" disabled="disabled">
                  <template slot="prepend">编码:</template>
                </el-input>
              </el-row>
              <el-row>
                <el-input v-model="non_drug_model_info.aim" disabled="disabled">
                  <template slot="prepend">简介:</template>
                </el-input>
              </el-row>
            </div>
          </el-tab-pane>
          <el-tab-pane label="常用检查项" name="non_drug_model_info">
            <el-table :data="usedList"  @row-click="choseNonDrug" >
              <el-table-column label="id" v-if="false" align="center" prop="id"/>
              <el-table-column label="项目名称" align="center" prop="name"/>
              <el-table-column v-if="queryParams.projectType!=4" label="单价" align="center" prop="price"/>
              <el-table-column v-if="queryParams.projectType==4" label="ICD编码" align="center" prop="icd"/>
              <el-table-column label="项目编码" align="center" prop="code"/>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <!-- 添加处置项目弹窗 -->
    <el-dialog :title="title" :visible.sync="open"  append-to-body>
      <el-row>
        <el-col :span="8" style="margin-right: 10px"><el-input  v-model="nonDrugQueryParams.name" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="3"><el-button @click="getNonDrugList" icon="el-icon-search" size="mini" type="cyan">搜索</el-button></el-col>
        <el-col :span="3"><el-button @click="nonDrugRest" icon="el-icon-refresh" size="mini">重置</el-button></el-col>
      </el-row>
      <el-table :data="non_drugList"   @row-click="choseNonDrug" style="max-height: 500px;overflow: auto;min-height: 500px">
        <el-table-column align="center" label="ID" prop="id" v-if="false"/>
        <el-table-column align="center" label="项目编码" prop="code"/>
        <el-table-column align="center" label="项目名称" prop="name"/>
        <el-table-column align="center" label="价格" prop="price"/>
      </el-table>
    </el-dialog>
    <!--检查执行-->
    <el-dialog  :title="title" class="app-container" :visible.sync="dealWithAddOpen"  append-to-body>
      <el-form :model="nonDealWithNonDrug" ref="nonDealWithNonDrug" :rules="rules" label-width="80px" size="mini">
        <el-row>
          <el-col :span="11">
            <el-form-item label="项目编码" prop="code">
              <el-input v-model="nonDealWithNonDrug.code" disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="nonDealWithNonDrug.name" disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="执行科室" prop="deptName">
              <el-input v-model="nonDealWithNonDrug.deptName" disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="目的" prop="aim">
              <el-input v-model="nonDealWithNonDrug.aim"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="要求" prop="demand">
              <el-input v-model="nonDealWithNonDrug.demand"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="临床印象" prop="clinicalImpression">
              <el-input v-model="nonDealWithNonDrug.clinicalImpression"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="临床诊断" prop="clinicalDiagnosis">
              <el-input v-model="nonDealWithNonDrug.clinicalDiagnosis"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="检查部位" prop="checkParts">
              <el-input v-model="nonDealWithNonDrug.checkParts"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item  size="large"  class="top-right-btn">
              <el-button type="primary" @click="CheckExecution">立即创建</el-button>
              <el-button @click="dealWithAddOpen=false">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {dealWithListNon_drug_item_record,addNon_drug_item_record,delNon_drug_item_record,save,del,getRedis} from "@/api/dms/non_drug_item_record";
  import {listNon_drug_model,getNon_drug_model} from "@/api/dms/non_drug_model";
  import {listNon_drug,getNon_drug} from "@/api/dms/non_drug";
  import {listUsed} from "@/api/dms/used";


  export default {
    name: "dealWithNonDrugItemRecord",
    /** 接收父组件传参*/
   // props:["registrationId"],

    data(){
      return{
          /** 医生常用诊断（疾病）、检查检验(搁置)表格数据*/
          usedList: [],
          /**检查项的非药品项目——数据表格*/
          tableData:[],
          /**非药品总金额*/
          amounts:0,
          /**模版集合*/
          nonDrug_modelList: [],
          /**模板参数 用于查询模板*/
          models: {type: 2},
          /**模板明细详情*/
          non_drug_model_info:{},
          /**处置状态字典数据*/
          statusList:[],
          /**新增处置是否显示弹出层*/
          open: false,
          /**处置执行,添加数据弹出层*/
          dealWithAddOpen:false,
          /**非药品数据表格(处置)*/
          non_drugList:[],
          /**非药品查询参数*/
          nonDrugQueryParams: {
            pageNum: null,
            pageSize: null,
            code: null,
            name: null,
            mnemonicCode: null,
            recordType: 3,
            deptId: null
          },
          /**选中数组*/
          ids: [],
          /**非单个禁用*/
          single: true,
          /**非多个禁用*/
          multiple: true,
          /**查询参数*/
          queryParams: {
            pageNum: 1,
            pageSize: 10,
            projectType: 1,
            id:null,
            name:null
          },
          /**检查执行表单参数*/
          nonDealWithNonDrug:{
            code:null,
            name:null,
            deptName:null,
            aim:null,
            demand:null,
            clinicalImpression:null,
            clinicalDiagnosis:null,
            checkParts:null,
            status:4,//检查已执行
            noDrugId:null,
            type:2,
            excuteDeptId:null,
            amount:null,
            registrationId:null,//挂号ID
          },
          /**弹出窗标题*/
          title:'',
          /**处置状态(常量)*/
          status:3,
          /**挂号Id*/
          registrationId:1,
          /**表单校验*/
          rules: {
            code: [
              { required: true, message: "项目编码不能为空", trigger: "blur" }
            ],
            name: [
              { required: true, message: "项目名称不能为空", trigger: "blur" }
            ],
            deptName: [
              { required: true, message: "执行科室不能为空", trigger: "blur" }
            ],
            aim: [
              { required: true, message: "目的不能为空", trigger: "blur" }
            ],
            demand: [
              { required: true, message: "要求不能为空", trigger: "blur" }
            ],
            clinicalImpression: [
              { required: true, message: "临床印象不能为空", trigger: "blur" }
            ],
            clinicalDiagnosis: [
              { required: true, message: "临床诊断不能为空", trigger: "blur" }
            ],
            checkParts: [
              { required: true, message: "检查部位不能为空", trigger: "blur" }
            ]
          }

    }
    },

    created() {
      /** 通过患者Id查询检查项 */
      this.getList();
      /**查询模版集合*/
      this.getMedicineModelList();
      /**处置字典表状态*/
      this.getDicts("non_drug_item_record_status").then(response => {
        this.statusList = response.data;
      });
      /**查询所有非药品，的处置信息*/
      this.getNonDrugList();
      /**常用项数据表格*/
      this.usedListLoad();
    },

    methods:{
      /** 通过挂号Id查询检查项 */
      getList() {
        this.loading = true;
        //父组件传参this.reregistrationId
        let param={"registrationId":this.registrationId,"type":2};
        dealWithListNon_drug_item_record(param).then(response => {
          this.tableData = response.rows;

        }).then(async()=>{
          this.getInfoByRedis();
          this.dealWithPrice();
        });
      },

      /**金额计算*/
      dealWithPrice(){
        let price=0;
        this.tableData.forEach(function(val, index, arr){
          price+=val.nonDrug.price;
        });
        this.amounts=price;
      },

      /**查询模版集合*/
      getMedicineModelList() {
        listNon_drug_model(this.models).then(response => {
          this.nonDrug_modelList = response.rows;
        });
      },

      /**通过模板Id查看非药品模板详情*/
      getNonDrugModelById(row, event, column){
        //通过模板Id查看非药品模板详情
        getNon_drug_model(row.id).then(response => {
          this.non_drug_model_info=response.data;
        });

        //通过模板ID添加非药品信息
        this.$confirm('是否确添加"' + row.name + '"到改患者?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).
        then(async() =>{
          //根据模板Id查询非药品信息
          getNon_drug_model(row.id).then(response =>{
            const nonDrugIdList=response.data.nonDrugIdList.split(',');
            nonDrugIdList.forEach(item=>{
              if(this.choseTableData(item)){//如果药品不重复才添加
                /*根据ID查询非药品信息*/
                getNon_drug(item).then(response => {
                  this.save(this.registrationId,response.data,this.status);//存入Redis中(挂号ID,药品数据,处置Id3)
                  this.tableData.push({
                    id:null,//处置申请明细ID
                    nonDrug:{
                      id:response.data.id,
                      code : response.data.code,
                      name : response.data.name,
                      deptName : response.data.deptName,
                      format : response.data.format,
                      price : response.data.price,
                      deptId:response.data.deptId,
                    },//药品信息
                    status:response.data.status,//状态
                    noDrugId:response.data.id//非药品ID
                  });
                  this.dealWithPrice();//金额计算
                });
              }
            })
          });
        }).then(async() =>{
          this.open=false;
        }).catch(function() {});
      },

      /** 状态字典翻译*/
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusList, row.status);
      },

      /**项目检查弹框*/
      showNonDrug(row){
        this.dealWithAddOpen=true;
        this.title="填写检查要求";
        this.nonDealWithNonDrug={
          code:row.nonDrug.code,
          name:row.nonDrug.name,
          deptName:row.nonDrug.deptName,
          aim:null,
          demand:null,
          clinicalImpression:null,
          clinicalDiagnosis:null,
          checkParts:null,
          status:4,//检查已执行
          noDrugId:row.nonDrug.id,
          type:2,
          excuteDeptId:row.nonDrug.deptId,
          amount:row.nonDrug.price,
          registrationId:this.registrationId,//挂号ID
        };
      },

      /** 新增按钮操作 */
      nonDrugTableOpenAndClose() {
        this.open = true;
        this.title = "处置目录";
      },

      /** 查询非药品收费项目列表(recordType==3) */
      getNonDrugList() {
        listNon_drug(this.nonDrugQueryParams).then(response => {
          this.non_drugList = response.rows;
        });
      },

      /**非药品列表查询参数清空*/
      nonDrugRest(){
        this.nonDrugQueryParams= {
          pageNum: null,
          pageSize: null,
          code: null,
          name: null,
          mnemonicCode: null,
          recordType: 3,
          deptId: null
        }
        this.getNonDrugList();
      },

      /**非药品表格点击传值*/
      choseNonDrug(row, event, column){
        //项目查重
        if(this.choseTableData(row.id)){
          this.$confirm('是否确添加"' + row.name + '"到该患者?', "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(async() =>{
            /*根据ID非药品信息*/
            getNon_drug(row.id).then(response => {
              this.save(this.registrationId,response.data,this.status);//存入Redis中(挂号ID,药品数据,处置Id3)
              this.tableData.push({
                id:null,//处置申请明细ID
                nonDrug:response.data,//药品信息
                status:response.data.status,//状态
                noDrugId:response.data.id//非药品ID
              });
              this.dealWithPrice();//金额计算
            });
          }).then(async() =>{
            this.open=false;
          }).catch(function() {});
        }
      },

      /**多选框选中数据*/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.noDrugId);//非药品ID
        this.single = selection.length!==1
        this.multiple = !selection.length
      },

      /**从处置列表里删除非药品信息(与数据库无关)*/
      delDrugInDealWithDrugTable(){
        //只有id为null(数据未入数据库),并且Ids(非药品ID)对应时
        const ids=this.ids;
        const tableData= this.tableData;
        for(let i=0;i<ids.length;i++){
          for(let j=0;j<tableData.length;j++){
            if(tableData[j].id==null && ids[i]==tableData[j].noDrugId){
              //删除页面数据
              this.tableData.splice(j,1);
              //删除Redis中数据
              getNon_drug(ids[i]).then(response=>{
                this.del(this.registrationId,response.data,this.status);
              });
            }
          }
        }
        /**删除完清空*/
        this.ids=[];
        /**金额结算*/
        this.dealWithPrice();
      },

      /**tableData数据表格查重*/
      choseTableData(id){
        let flag=true;
        this.tableData.findIndex((value, index, arr) => {
          var that = this;//暂存This，function(){}防止函数内取不到值
          if(value.nonDrug.id==id){
            setTimeout(function () {//延时操作，页面显示
              that.$message.error(value.nonDrug.name+"已存在,无需重复添加！");
            },100);
            flag=false;
            return;
          }
        })
        return flag;
      },

      /**常用项数据加载*/
      usedListLoad(){
        listUsed(this.queryParams).then(response => {
          this.usedList = response.rows;
        });
      },

      /**执行表单提交*/
      CheckExecution(){
        this.$refs['nonDealWithNonDrug'].validate((valid) =>{
          if (valid) {
            addNon_drug_item_record(this.nonDealWithNonDrug).then(response=>{
              if (response.code === 200) {
                this.msgSuccess("添加成功");
                this.dealWithAddOpen = false;
                //删除Redis中数据
                getNon_drug(this.nonDealWithNonDrug.noDrugId).then(response=>{
                  this.del(this.registrationId,response.data,this.status);
                });
                this.getList();
              }
            })
          }
        })


      },

      /**开立项目*/
      addDrugInDealWithDrug() {
        var that = this;//暂存This，function(){}防止函数内取不到值
        //只有id为null(数据未入数据库),并且Ids(非药品ID)对应时
        const ids = this.ids;
        const tableData = this.tableData;
        for (let i = 0; i < ids.length; i++) {
          for (let j = 0; j < tableData.length; j++) {
            if (tableData[j].id == null && ids[i] == tableData[j].noDrugId) {
              //删除Redis中数据
              getNon_drug(ids[i]).then(response=>{
                this.del(this.registrationId,response.data,this.status);
              });
              //开立数据
              this.nonDealWithNonDrug={
                code:tableData[j].nonDrug.code,
                name:tableData[j].nonDrug.name,
                deptName:tableData[j].nonDrug.deptName,
                aim:null,
                demand:null,
                clinicalImpression:null,
                clinicalDiagnosis:null,
                checkParts:null,
                status:4,//检查已执行
                noDrugId:tableData[j].nonDrug.id,
                type:2,//未缴费
                excuteDeptId:tableData[j].nonDrug.deptId,
                amount:tableData[j].nonDrug.price,
                registrationId:this.registrationId,//挂号ID
              };
              addNon_drug_item_record(this.nonDealWithNonDrug).then(response=>{
                if (response.code === 200) {
                  setTimeout(function () {//延时操作，页面显示
                    that.msgSuccess(tableData[j].nonDrug.name+"添加成功");                  },100);
                }
              }).then(async()=>{
                this.getList();
              } );
            }
          }
        }
      },

      /**作废处方*/
      delDrugDealWith(){
        var that = this;//暂存This，function(){}防止函数内取不到值
        //只有id为null(数据未入数据库),并且Ids(非药品ID)对应时
        const ids = this.ids;
        const tableData = this.tableData;
        let drugIDs=[];
        for (let i = 0; i < ids.length; i++) {
          for (let j = 0; j < tableData.length; j++) {
            if (tableData[j].id != null && ids[i] == tableData[j].noDrugId) {//如果：（tableData[j].id != null）是入了数据库的数据
              drugIDs.push(tableData[j].id);
            }
          }
        }
        //如果有选中的符合条件的值，才删除
        if(drugIDs.length>0){
          delNon_drug_item_record(drugIDs).then(response=>{
            if(response.code==200){
              that.msgSuccess("操作成功");
            }
          }).then(async()=>{
            this.getList();
          } );
        }

      },

      /**暂存Redis(挂号ID,药品信息)*/
      save(registrationId,data,status){
        save(data,registrationId,status);
      },

      /**删除Redis缓存*/
      del(registrationId,data,status){
        del(data,registrationId,status);
      },

      /**通过挂号ID进行Redis缓存加载*/
      getInfoByRedis(){
        getRedis(this.registrationId,this.status).then(response=>{
          response.data.forEach( (data,index,array)=>{
            this.tableData.push({
              id:null,//处置申请明细ID
              nonDrug:data,//药品信息
              status:data.status,//状态
              noDrugId:data.id//非药品ID
            });
          })
        });
      }
    }
  }
</script>

<style scoped>
  #doWith i{
    width: 120px;
    font-size: 20px;
    text-align: center;
    line-height: revert;
    line-height: initial;
  }
  .menu>button{
    font-size: 17px;
    font-weight: bold;
    color: #409EFF;
    padding-right: 22px;
  }
  .menu{
    background-color: #F2F6FC;
    padding: 15px;
  }
</style>
